import { Component } from 'inferno'
import './Popup.css'

interface State {
  count: number
}

export class Popup extends Component<unknown, State> {
  link = 'https://github.com/guocaoyi/create-chrome-ext'
  state: State = { count: 0 }

  constructor(props: unknown) {
    super(props)

    chrome.storage.sync.get(['count'], (result) => {
      this.setState({ count: result.count || 0 })
    })
  }

  minus = () => {
    if (this?.state?.count > 0) {
      this.setState({ count: --this.state.count })
    }
  }

  add = () => this.setState({ count: ++this.state.count })

  componentDidUpdate(_: any): void {
    chrome.storage.sync.set({ count: this.state.count })
    chrome.runtime.sendMessage({ type: 'COUNT', count: this.state.count })
  }

  render() {
    return (
      <main>
        <h3>Popup Page</h3>
        <div className="calc">
          <button onClick={this.minus} disabled={this.state.count <= 0}>
            -
          </button>
          <label>{this.state.count}</label>
          <button onClick={this.add}>+</button>
        </div>
        <a href={this.link} target="_blank">
          generated by create-chrome-ext
        </a>
      </main>
    )
  }
}

export default Popup
